<?php

namespace app\shop\controller;

use app\api\service\WechatMiniService;
use app\common\model\Account;
use app\common\model\ShopOrderTip;
use app\common\model\ShopStore;
use app\common\service\Status;
use app\common\model\ShopMember;
use app\shop\model\ShopGoods;
use app\shop\model\ShopOrder;
use app\shop\model\ShopOrderGoods;
use app\common\model\ShopUserMoneyRecord;
use buildView\Actions;
use buildView\Button;
use buildView\Filter;
use library\tools\Data;
use think\Controller;
use buildView\Detail;
use buildView\Form;
use buildView\Grid;
use app\shop\model\ShopOrderRefund;
use think\Db;
use think\Exception;
use think\facade\Cache;
use think\facade\Cookie;

/**
 * 售后订单管理
 * Class OrderRefund
 * @package app\shop\controller
 */
class OrderRefund extends Controller
{
    /**
     * 列表
     * @auth true
     * @menu true
     * @return string
     */
    public function index()
    {
        $store = session('store');
        $grid = new Grid(new ShopOrderRefund);
        if ($store){
            $grid->model()->where('store_id',$store['id']);
        }
        $grid->setTitle('售后订单管理');
        $grid->user()->headimg('会员')->display(function ($val, $data, $html) {
            return $html . '<br>' . $data['user']['nickname'];
        })->setExcelData(function($val,$data){
            return $data['user']['nickname'];
        })->image(50);
        if (!$store){
            $grid->store()->name('门店');
        }
        $grid->order()->order_no('订单号');
        $grid->order()->pay_type('支付方式')->using(Status::PAYTYPE())->badge();
        $grid->type('售后类型')->using(Status::REFUNDTYPE());
        $grid->status('售后状态')->using(Status::REFUNDSTATUS())->badge();
        $grid->price('退款金额');
        $grid->create_at('申请时间');
        $grid->actions(function (Actions $action, $data) {
            $action->width(300);
            $action->hideEdit();
            $action->hideDel();
            if ($data['type'] == 1 && $data['status'] == 1) {
                $button = new Button('同意退款');
                $button->save($data['id'], ['status' => 4], url('passRefund'), '确认退款？');
                $action->append($button);
                $button = new Button('拒绝退款', 'danger');
                $button->href(url('refused') . "?id={$data['id']}", 'modal');
                $action->append($button);
            }
        });
        $grid->hideDeletesButton();
         $grid->filter(function (Filter $filter)use($store) {
            if (!$store) {
                $data = ShopStore::field('id,name')->column('name','id');
                $filter->eq('store_id', '门店')->select($data);
            }
            $filter->eq('order.order_no', '订单号');
            $filter->eq('type', '售后类型')->select(Status::REFUNDTYPE());
            $filter->eq('status', '售后状态')->select(Status::REFUNDSTATUS());
        });
        $grid->setFromOpen();
        $grid->hideAddButton();

        return $grid->view();
    }

    /**
     * 同意退款
     * @auth true
     * @menu true
     * 2019/10/8 17:08
     */
    public function passRefund()
    {
        $refund_id = $this->request->post('id');
        $refund = ShopOrderRefund::where('status', 1)->get($refund_id, ['order']);
        // halt($refund);
        
        if ($refund) {
            $order = $refund['order'];
            Db::startTrans();
            try {
                if ($order['pay_type'] == 1){
/*=======bug====>*/$res = WechatMiniService::refund($order['pay_no'],$order['order_no'],$order['total_price'],$refund['price']);
                    if ($res) {
                        $refund->status = 4;
                        $refund->complete_time = date('Y-m-d H:i:s');
                        $refund->save();
                        ShopOrder::where('id', $order['id'])->setField('status', -1);
                        ShopOrderGoods::where('order_id', $order['id'])->setField('status', 2);
                        Account::create([
                            'uid' => $order['uid'],
                            'title' => "{$order['title']}",
                            'desc' => "退款微信钱包 - 订单号：{$order['order_no']}",
                            'money' => $refund['price'],
                            'type' => 2,
                            'store_id' => $order['store_id'],
                            'order_id' => $order['id']
                        ]);
                        $data = [
                            'order_id' => $order['id'],
                            'uid' => $order['uid'],
                            'title' => '退款成功',
                            'content' => "¥{$order['total_price']}已成功退回到支付账户"
                        ];
                    }else {
                        Db::rollback();
                        $this->error('失败1001', '');
                    }
                }elseif ($order['pay_type'] == 3){
                    // halt("3333");
                    $refund->status = 4;
                    $refund->complete_time = date('Y-m-d H:i:s');
                    $refund->save();
                    ShopOrder::where('id', $order['id'])->setField('status', -1);
                    ShopOrderGoods::where('order_id', $order['id'])->setField('status', 2);
                    Account::create([
                        'uid' => $order['uid'],
                        'title' => "{$order['title']}",
                        'desc' => "退款余额钱包 - 订单号：{$order['order_no']}",
                        'money' => $refund['price'],
                        'type' => 2,
                        'store_id' => $order['store_id'],
                        'order_id' => $order['id']
                    ]);
                    ShopUserMoneyRecord::record($order['total_price'],$order['uid'],"预约退款",1,true,"余额支付 - 订单号：{$order['order_no']}");
                    $data = [
                        'order_id' => $order['id'],
                        'uid' => $order['uid'],
                        'title' => '退款成功',
                        'content' => "¥{$order['total_price']}已成功退回到账户余额"
                    ];
                }else{
                    $refund->status = 4;
                    $refund->complete_time = date('Y-m-d H:i:s');
                    $refund->save();
                    $buy_num = ShopOrderGoods::where('order_id',$order['id'])->sum('num');
                    ShopOrderGoods::where('order_id', $order['id'])->setField('status', 2);
                    $rs =ShopMember::where('uid', $order['uid'])->where('status',1)->setDec('use_num', $buy_num);
                    $data = [
                        'order_id' => $order['id'],
                        'uid' => $order['uid'],
                        'title' => '审核成功',
                        'content' => "总{$buy_num}件数已成功退回到账户件数"
                    ];
                }
                ShopOrderTip::create($data);
                Db::commit();
                $this->success('成功');
            } catch (Exception $e) {
                Db::rollback();
                $this->error('失败1002:'.$e->getMessage(), '');
            }
        } else {
            $this->error('售后失败，订单无效', '');
        }
    }
    
    /**
     * 拒绝售后
     * @auth true
     * @menu true
     */
    public function refused()
    {
        $form = new Form(new ShopOrderRefund);
        $refund_id = $this->request->get('id');
        $form->textarea('content', '拒绝理由');
        $form->hidden('status', '状态')->value(0);
        $info = ShopOrderRefund::get($refund_id);
        // ShopOrder表status字段更新为2，重新进行洗衣
        $order_status = ShopOrder::where('id',$info['order_id'])->update(['status'=>2]);
        $data = [
            'order_id' => $info['order_id'],
            'uid' => $info['uid'],
            'title' => '审核失败',
            'content' => "审核不通过原因：{$info['content']}"
        ];
        ShopOrderTip::create($data);
        return $form->view();
    }

    /**
     * 详情
     * @auth true
     * @menu true
     * @return string
     */
    public function detail()
    {
        $detail = new Detail(new ShopOrderRefund);
        $data = $detail->getModelData();
        if ($data['type'] == 2) {
            $md = 6;
        } else {
            $md = 12;
        }
        $detail->layout('售后信息', $md, function ($detail) use ($data) {
            if ($data['type'] == 1 && $data['status'] == 1) {
                $detail->column('action', '')->display(function () use ($data) {
                    $html = '';
                    $button = new Button('同意退款');
                    $button->save($data['id'], ['status' => 2], url('passRefund'), '确认退款？');
                    $html .= $button->render();
                    $button = new Button('拒绝退款', 'danger');
                    $button->href(url('refused') . "?id={$data['id']}", 'modal');
                    $html .= $button->render();
                    return $html;
                });
            }
            $detail->user()->nickname('会员昵称');
            $detail->user()->headimg('会员头像')->image(50, 50, 50);
            $detail->type('售后类型')->using(Status::REFUNDTYPE());
            $detail->order()->order_no('订单号');
            $detail->status('售后状态')->using(Status::REFUNDSTATUS())->badge();
            $detail->price('退款金额');
            $detail->refund_price('实际退款金额');
            $detail->img('售后图片凭证')->image();
            $detail->desc('申请售后描述');
            $detail->create_at('申请时间');
            $detail->complete_time('完成时间');
        });
        if ($data['type'] == 2) {
            $detail->layout('换货地址', 6, function ($detail) {
                $detail->address_info()->name('姓名');
                $detail->address_info()->phone('联系电话');
                $detail->address_info('地址')->display(function ($val) {
                    return "{$val['province']}{$val['city']}{$val['area']}{$val['address']}";
                });
            });
            $detail->layout('用户寄回', 6, function ($detail) {
                $detail->express_compay('快速公司');
                $detail->express_number('快递单号');
            });
        }
        return $detail->view();
    }
}
